package stack

type Stack struct {
	top     int
	data    []interface{}
	maxSize int
}

func NewStack(maxSize int) *Stack {
	return &Stack{
		top:     -1,
		data:    make([]interface{}, maxSize),
		maxSize: maxSize,
	}
}

func (s *Stack) Push(item interface{}) error {
	if s.top == s.maxSize-1 { //满
		return stackFull
	}

	s.top++
	s.data[s.top] = item
	return nil

}

func (s *Stack) Pop() (interface{}, error) {
	if s.top == -1 {
		return nil, stackEmpty
	}

	data := s.data[s.top]
	s.top--
	return data, nil

}

//清空方法
func (s *Stack) Clear() {

	for i := 0; i < s.top; i++ {
		s.data[i] = nil
	}

	s.top = -1
}

//返回个数
func (s *Stack) Length() int {
	return s.top + 1
}

//判断空
func (s *Stack) Empty() bool {
	if s.top == -1 {
		return true
	}

	return false
}

//返回元素
func (s *Stack) GetTop() (interface{}, error) {
	if s.top == -1 {
		return nil, stackEmpty
	}

	return s.data[s.top], nil

}

//链栈
type Node struct {
	Data interface{}
	Next *Node
}

type LinkStack struct {
	top *Node
	len int
}

func NewLinkStack() *LinkStack {
	return &LinkStack{
		top: nil,
		len: 0,
	}
}

func (l *LinkStack) Push(item interface{}) {
	node := Node{Data: item, Next: l.top}
	l.top = &node
	l.len++
}

func (l *LinkStack) Empty() bool {
	return l.len == 0
}

func (l *LinkStack) Clear() {
	l.top = nil
	l.len = 0
}

func (l *LinkStack) Length() int {
	return l.len
}

func (l *LinkStack) Pop() (interface{}, error) {
	if l.Empty() {
		return nil, stackEmpty
	}

	data := l.top.Data
	l.top = l.top.Next
	l.len--
	return data, nil

}

func (l *LinkStack) GetTop() (interface{}, error) {
	if l.Empty() {
		return nil, stackEmpty
	}

	return l.top.Data, nil

}
